package com.gqzm.side.common.socket;

import com.alibaba.fastjson2.JSON;
import com.gqzm.side.domain.bo.BoxMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName: {@link CloudPlatformSocketHandler}
 * @description: 边端盒子心跳处理
 * @author: peter qin
 * @date: 2023 09 07
 * @version: 1.0
 **/
@Slf4j
public class CloudPlatformSocketHandler extends SimpleChannelInboundHandler<String> {

    //定义一个channle 组，管理所有的channel
    //GlobalEventExecutor.INSTANCE) 是全局的事件执行器，是一个单例
    private static final ChannelGroup channelGroup =
            new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private static HashSet<Channel> channels = new HashSet<>();


    /**
     * 有客户端与服务器发生连接时执行此方法
     * 1.打印提示信息
     * 2.将客户端保存到 channelGroup 中
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.info("====客户端连接服务端，客户端地址为:{}", channel.remoteAddress());
        channelGroup.add(channel);
        channels.add(channel);
    }


    /**
     * 当有客户端与服务器断开连接时执行此方法，此时会自动将此客户端从 channelGroup 中移除
     * 1.打印提示信息
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String clientId = channel.remoteAddress().toString();
        log.info("====客户端断开连接，客户端地址为: {}", clientId);
        channels.remove(channel);
    }


    /**
     * 表示channel 处于活动状态
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.info("====客户端处于活动状态，客户端地址为:{}", channel.remoteAddress());
    }


    /**
     * 表示channel 处于不活动状态
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx)
            throws Exception {
        Channel channel = ctx.channel();
        log.info("====客户端处于不活动状态，客户端地址为:{}", channel.remoteAddress());
        channels.remove(channel);
    }


    /**
     * 处理异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        log.error("发生异常。异常信息：{}", cause.getMessage());
        //关闭通道
        ctx.close();
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx,
                                String msg) throws Exception {
        try {
            Channel channel = ctx.channel();
            String clientId = channel.remoteAddress().toString();
            log.info("msg length: {}", msg.length());
        } catch (Exception e) {
            log.error("服务的处理消息异常", e);
        }
    }


    /**
     * 发送消息
     * @param message
     */
    public static void pushMessage(BoxMessage message) {
//        channels.forEach(channel -> channel.writeAndFlush(msg));
        channelGroup.writeAndFlush(JSON.toJSONString(message));
    }


}
